package com.suyang.syt.controller;

import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.concurrent.ConcurrentTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suyang.syt.auth.AuthClass;
import com.suyang.syt.model.Message;
import com.suyang.syt.model.User;
import com.suyang.syt.model.dto.AjaxObj;
import com.suyang.syt.model.dto.MessageDTO;
import com.suyang.syt.model.dto.PagerEasyUI;
import com.suyang.syt.service.interfaces.MessageSpreadService;
import com.suyang.syt.util.DateFormat;
import com.suyang.syt.util.EmptyUtil;
import com.suyang.syt.util.StringUtil;

@AuthClass
@Controller
@RequestMapping("/admin/messageSpread")
public class AdminMessageSpreadController {

	@Autowired
	private MessageSpreadService messageSpreadService;

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "messageSpread/list";
	}

	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public PagerEasyUI<MessageDTO> list(HttpServletRequest request, int page, int rows, String sort, String order, String createDate1, String createDate2, String checkName, String checkStatus, String isTime) {
		try {
			return messageSpreadService.listByEasyUI(page, rows, sort, order, createDate1, createDate2, checkName, checkStatus, isTime);
		} catch (Exception e) {
			return null;
		}
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxObj add(HttpServletRequest request, final Message message) {
		try {
			if (message == null) {
				return new AjaxObj(0, "推送消息参数错误！");
			}
			User user = (User) request.getSession().getAttribute("loginUser");
			Date date = null;
			String time = message.getTiming();
			if (EmptyUtil.isNotEmpty(time)) {
				date = DateFormat.stringToDate(time);
				if (System.currentTimeMillis() >= date.getTime()) {
					return new AjaxObj(0, "定时时间不能小于当前时间!");
				}
			}
			if (date != null) {
				message.setIsTime(1);
				message.setCreateName(user.getUsername());
				message.setCreateTime(DateFormat.dateToString(new Date()));
				messageSpreadService.addTask(message);

				ScheduledExecutorService localExecutor = Executors.newSingleThreadScheduledExecutor();
				TaskScheduler taskScheduler = new ConcurrentTaskScheduler(localExecutor);
				Runnable runnable = new Runnable() {
					@Override
					public void run() {
						try {
							messageSpreadService.updateStatus(message.getId(), message.getTiming());
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				};
				taskScheduler.schedule(runnable, new CronTrigger(DateFormat.getCron(date)));
			} else {
				message.setStatus(1);
				message.setCreateName(user.getUsername());
				message.setCreateTime(DateFormat.dateToString(new Date()));
				messageSpreadService.addTask(message);
			}
			return new AjaxObj(1, "消息发送成功！！");
		} catch (Exception e) {
			return new AjaxObj(0, StringUtil.ERROR_MSG);
		}
	}

	@RequestMapping(value = "/timing", method = RequestMethod.POST)
	@ResponseBody
	public AjaxObj updateTiming(HttpServletRequest request, String ids) {
		try {
			if (EmptyUtil.isNotEmpty(ids)) {
				Message message = null;
				for (String id : ids.split(",")) {
					message = messageSpreadService.load(Long.parseLong(id));
					final long mid = message.getId();
					final String timing = message.getTiming();
					if (System.currentTimeMillis() < DateFormat.stringToDate(message.getTiming()).getTime()) {
						ScheduledExecutorService localExecutor = Executors.newSingleThreadScheduledExecutor();
						TaskScheduler taskScheduler = new ConcurrentTaskScheduler(localExecutor);
						Runnable runnable = new Runnable() {
							@Override
							public void run() {
								try {
									messageSpreadService.updateStatus(mid, timing);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						};
						taskScheduler.schedule(runnable, new CronTrigger(DateFormat.getCron(DateFormat.stringToDate(timing))));
					}
				}
				return new AjaxObj(1, "启动成功!");
			}
			return new AjaxObj(0, "请选择您要启动的任务!");
		} catch (Exception e) {
			e.printStackTrace();
			return new AjaxObj(0, StringUtil.ERROR_MSG);
		}
	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxObj delete(HttpServletRequest request, String ids) {
		try {
			return messageSpreadService.deletes(ids);
		} catch (Exception e) {
			return new AjaxObj(0, StringUtil.ERROR_MSG);
		}
	}

}
